<template>
	<view class="main">
        <view class="withdraw-box">
            <view class="tab-box" v-if="(currentIndex == 'login' || currentIndex == 'register') && type === '0'">
                <view class="tab" :class="{'tab-active': currentIndex == 'login'}" @click="currentIndex = 'login'">
                    {{$t('login.login')}}
                </view>
                <view class="tab" :class="{'tab-active': currentIndex == 'register'}" @click="currentIndex = 'register'">
                    {{$t('login.register')}}
                </view>
            </view>
            <view class="tab-box" v-else>
                <view v-if="type == '0'">
                    {{$t('login.setnew')}}
                </view>
                <view v-if="type == '1'">
                    {{$t('login.resetlogin')}}
                </view>
                <view v-if="type == '2'">
                    {{$t('login.resetwithdraw')}}
                </view>
            </view>
            <template v-if="currentIndex == 'login'">
            <view class="code">
                <view class="input-box">
                    <text style="color:#AAAAAA;padding-right: 20rpx;margin-right: 20rpx;border-right:2rpx solid #AAA;">{{$phonehead}}</text>
                    <u-input v-model="form.mobile"  :placeholder="$t('login.mobile')" type="number" 
                    :clearable='false' :custom-style="codestyle"/>
                </view>
            </view>
            <view class="code" v-if="loginStatus == 'codeAuth'">
                <view class="input-box">
                    <u-input v-model="form.code"  :placeholder="$t('login.code')" type="number" 
                    :clearable='false' :custom-style="codestyle"/>
                </view>
                <view class="otp">
                    <u-verification-code :seconds="seconds" :start-text="$t('my.otp')" :end-text="$t('my.otp')"
                    change-text="xs" @end="end" @start="start" ref="uCode" @change="codeChange"></u-verification-code>
                    <button @tap="getCode('login')" class="send_code" :class="[showNext ? 'codegray':'codeactive']">{{tips}}</button>
                </view>
            </view>
            <view class="code">
                <view class="input-box">
                    <u-input v-model="form.password"  :placeholder="$t('login.loginpassword')" type="password"
                    maxlength="12" :clearable='false' :passwordIcon="false" :myShowPassword="passwordShow"
                    :custom-style="codestyle"/>
                    <image src="../../static/image/eye/hide.png" style="width: 32rpx;height:12rpx;" mode="" @click="passwordShow = true" v-if="!passwordShow"/>
                    <image src="../../static/image/eye/show.png" style="width: 33rpx;height:24rpx;" mode="" @click="passwordShow = false" v-if="passwordShow"/>
                </view>
            </view>
            </template>
            <template v-if="currentIndex == 'register'">
                <view class="code">
                    <view class="input-box">
                        <text style="color:#AAAAAA;padding-right: 20rpx;margin-right: 20rpx;border-right:2rpx solid #AAA;">{{$phonehead}}</text>
                        <u-input v-model="form.mobile"  :placeholder="$t('login.mobile')" type="number" 
                        :clearable='false' :custom-style="codestyle"/>
                    </view>
                </view>
                <view class="code">
                    <view class="input-box">
                        <u-input v-model="form.code"  :placeholder="$t('login.code')" type="number" 
                        :clearable='false' :custom-style="codestyle"/>
                    </view>
                    <view class="otp">
                        <u-verification-code :seconds="seconds" :start-text="$t('my.otp')" :end-text="$t('my.otp')"
                        change-text="xs" @end="end" @start="start" ref="uCode" @change="codeChange"></u-verification-code>
                        <button @tap="getCode('register')" class="send_code" :class="[showNext ? 'codegray':'codeactive']">{{tips}}</button>
                    </view>
                </view>
                <view class="code">
                    <view class="input-box">
                    <u-input v-model="form.password"  :placeholder="$t('login.registerpassword')" type="password"
                    maxlength="12" :clearable='false' :passwordIcon="false" :myShowPassword="passwordShow"
                    :custom-style="codestyle"/>
                    <image src="../../static/image/eye/hide.png" style="width: 32rpx;height:12rpx;" mode="" @click="passwordShow = true" v-if="!passwordShow"/>
                    <image src="../../static/image/eye/show.png" style="width: 33rpx;height:24rpx;" mode="" @click="passwordShow = false" v-if="passwordShow"/>
                    </view>
                </view>
                <view class="code">
                    <view class="input-box">
                    <u-input v-model="form.re_password"  :placeholder="$t('login.repassword')" type="password"
                    maxlength="12" :clearable='false' :passwordIcon="false" :myShowPassword="repasswordShow"
                    :custom-style="codestyle"/>
                    <image src="../../static/image/eye/hide.png" style="width: 32rpx;height:12rpx;" mode="" @click="repasswordShow = true" v-if="!repasswordShow"/>
                    <image src="../../static/image/eye/show.png" style="width: 33rpx;height:24rpx;" mode="" @click="repasswordShow = false" v-if="repasswordShow"/>
                    </view>
                </view>
                <view class="code">
                    <view class="input-box">
                    <u-input v-model="form.invite_code"  :placeholder="$t('login.invite')"
                    maxlength="12" :clearable='false' :passwordIcon="false" :disabled="codeDisabled"
                    :custom-style="codestyle"/>
                    </view>
                </view>
            </template>
            <template v-if="currentIndex == 'reset'">
                <view class="code">
                    <view class="input-box">
                    <text style="color:#AAAAAA;padding-right: 20rpx;margin-right: 20rpx;border-right:2rpx solid #AAA;">{{$phonehead}}</text>
                    <u-input v-model="form.mobile"  :placeholder="$t('login.mobile')" type="number" :disabled="type != '0'"
                    :clearable='false' :custom-style="codestyle"/>
                    </view>
                </view>
                <view class="code">
                    <view class="input-box">
                    <u-input v-model="form.code"  :placeholder="$t('login.code')" type="number" 
                    :clearable='false' :custom-style="codestyle"/>
                    </view>
                    <view class="otp">
                        <u-verification-code :seconds="seconds" :start-text="$t('my.otp')" :end-text="$t('my.otp')"
                        change-text="xs" @end="end" @start="start" ref="uCode" @change="codeChange"></u-verification-code>
                        <button @tap="getCode('reset')" class="send_code" :class="[showNext ? 'codegray':'codeactive']">{{tips}}</button>
                    </view>
                </view>
                <view class="code">
                    <view class="input-box">
                    <u-input v-model="form.password"  :placeholder="$t('login.registerpassword')" type="password"
                    maxlength="12" :clearable='false' :passwordIcon="false" :myShowPassword="passwordShow"
                    :custom-style="codestyle"/>
                    <image src="../../static/image/eye/hide.png" style="width: 32rpx;height:12rpx;" mode="" @click="passwordShow = true" v-if="!passwordShow"/>
                    <image src="../../static/image/eye/show.png" style="width: 33rpx;height:24rpx;" mode="" @click="passwordShow = false" v-if="passwordShow"/>
                    </view>
                </view>
                <view class="code">
                    <view class="input-box">
                    <u-input v-model="form.re_password"  :placeholder="$t('login.repassword')" type="password"
                    maxlength="12" :clearable='false' :passwordIcon="false" :myShowPassword="repasswordShow"
                    :custom-style="codestyle"/>
                    <image src="../../static/image/eye/hide.png" style="width: 32rpx;height:12rpx;" mode="" @click="repasswordShow = true" v-if="!repasswordShow"/>
                    <image src="../../static/image/eye/show.png" style="width: 33rpx;height:24rpx;" mode="" @click="repasswordShow = false" v-if="repasswordShow"/>
                    </view>
                </view>
            </template>
            <view class="bottom-box link" v-if="currentIndex == 'login'">
                <view @click="currentIndex = 'reset'"  >{{$t('login.reset')}}</view>
            </view>
            <view class="bottom-box link"  v-if="currentIndex == 'reset' && type == '0'">
                 <view @click="currentIndex = 'login'">{{$t('login.back')}}</view>
            </view>
        </view>
        <view class="confirm" @click="login" v-if="currentIndex == 'login'">
            {{$t('login.login')}}
        </view>
        <view class="confirm" @click="reset" v-if="currentIndex == 'reset' && type != '2'">
            {{$t('login.confirm')}}
        </view>
        <view class="confirm" @click="register" v-if="currentIndex == 'register'">
            {{$t('login.register')}}
        </view>
        <view class="confirm" @click="resetwithdraw" v-if="currentIndex == 'reset' && type == '2'">
            {{$t('login.confirm')}}
        </view>
        <u-icon class="backicon" name="arrow-left" @click="backToHome" color="#fff" size="44"></u-icon>
        <image src="@/static/image/eye/tl_bg.png" style="position:fixed;top:0;left:0;width:444rpx;height:227rpx;z-index:-1;" mode="" />
        <image src="@/static/image/eye/br_bg.png" style="position:fixed;bottom:0;right:0;width:368rpx;height:132rpx;z-index:-1;" mode="" />
	</view>
</template>

<script>
    // #ifdef APP-PLUS
	var appsFlyer = uni.requireNativePlugin("sn-appsflyer");
	// #endif
    import {
		Login,
		Register,
        resetpwd,
		sendreset,
        sendsms,
        resetwithdrawcode,
        resetwithdraw,
        authentication,
        checkauthentication
	} from '@/api/auth.js'
    import { toast } from 'uview-ui';
	export default {
		data() {
			return {
                show: false,
                codeDisabled: false,
                codestyle:{
                    flex:1,
					borderRadius:' 10rpx',
					fontSize: '28rpx',
					fontFamily:' Rubik',
					fontWeight: '400',
					height:'90rpx',
				},
                form: {
                    mobile: '15659438888',
					password: '123456',
                    re_password: '',
                    code: '',
                    invite_code: '',
                    agent: ''
                },
                passwordShow: false,
                repasswordShow: false,
                currentIndex: 'login',
                seconds: 60,
                tips: '',
                showNext: false,
                loginStatus: ''
			};
		},
        props: {
            showPopup: {
                type: Boolean,
                default: false
            },
            type: {//0登陆注册 1重置密码 2提现密码
                type: String,
                default: '0',
            }
        },
        watch: {
            showPopup() {
				this.show = true
			},
            currentIndex() {
                for (let i in this.form) {
                    this.form[i] = ''
                }
                this.form.invite_code = uni.getStorageSync('invite_code');
                this.form.agent = uni.getStorageSync('agent_code');
            }
		},
        onLoad(option) {
            this.form.invite_code = uni.getStorageSync('invite_code') || '';
            this.form.agent = uni.getStorageSync('agent_code') || '';
            // #ifdef APP-PLUS
                let that = this;
                plus.device.getInfo({  
                    success: function(e) {  
                        let obj = JSON.parse(JSON.stringify(e)); 
                        console.log(obj.uuid)
                        that.$store.commit('SET_CLIENTID',obj.uuid)
                    },  
                    fail: function(e) {  
                    }  
                });
                // #endif
            if (option.currentIndex) {
                this.currentIndex = option.currentIndex;
            }
            if (option.invite_code) {
                this.form.invite_code = option.invite_code;
                uni.setStorageSync('invite_code', option.invite_code)
                this.codeDisabled = true;
            }
            if (option.agent) {
                this.form.agent = option.agent;
                uni.setStorageSync('agent_code', option.agent)
            }
        },
        mounted() {
            console.log(this.type)
            if (this.type == '1' || this.type == '2') {
                this.currentIndex = 'reset'
            }
        },
        computed: {
            phoneReg() {
                return this.form.mobile&&this.form.mobile.length < 12;
				let reg = new RegExp(/^(\d{3,4}-?){2}\d{3,4}$/g)
				return reg.test(this.mobile);
			},
            
            userInfo() {
                let userInfo = this.$store.getters.userInfo || {};
                this.form.mobile = userInfo.mobile || ''
                return  userInfo
            }
        },
		methods: {
            pwdRex(val) {
				return /^[A-Za-z0-9]{6,16}$/.test(val)
			},
            async login() {
                console.log(this.$store.state.clientid)
                uni.showLoading({
                });
                let api;
                if (this.loginStatus == 'codeAuth') {
                    api = checkauthentication
                    try {
                        let result = await api({
                            mobile: this.form.mobile,
                            password: this.form.password,
                            device_id: this.$store.state.clientid,
                            code: this.loginStatus == 'codeAuth'?this.form.code:undefined
                        })
                        this.loginStatus = ''
                        this.login();
                    } catch (error) {
                        uni.hideLoading();
                    }
                } else {
                    api = Login
                    try {
                        let result = await api({
                            mobile: this.form.mobile,
                            password: this.form.password,
                            device_id: this.$store.state.clientid,
                            code: this.loginStatus == 'codeAuth'?this.form.code:undefined
                        })
                        uni.setStorage({ 
                            key: 'guideFlag', 
                            data: false, 
                        }); 
                        uni.setStorageSync('overwindow', 0)
                        this.$store.commit('SET_RECOMM', true)
                        this.$store.dispatch('setToken', result.userinfo.token);
                        this.$store.dispatch('setUserInfo', result.userinfo);
                        this.$store.dispatch('getSystemInfo');
                        
                        uni.hideLoading();
                        uni.showToast({
                            icon: 'none',
                            title: 'Success',
                            position: 'center',
                            duration: 2000
                        })
                        this.back();
                        this.show = false;
                    } catch (error) {
                        if (error.status == '5') {
                            this.loginStatus = 'codeAuth'
                        }
                        uni.hideLoading();
                    }
                }
                console.log(this.$store.state.clientid)
			},
            async reset() {
                uni.showLoading({
                });
                try {
                    let result = await resetpwd({
                        mobile: this.form.mobile,
                        password: this.form.password,
                        re_password: this.form.re_password,
                        code: this.form.code,
                    })
                    uni.hideLoading();
                    uni.showToast({
                        icon: 'none',
                        title: this.$t('tips.success'),
                        position: 'center',
                        duration: 2000
                    })
                    this.currentIndex = 'login';
                    this.show = false;
                } catch (error) {
                    uni.hideLoading();
                }
                
			},
            async resetwithdraw() {
                uni.showLoading({
                });
                try {
                    let result = await resetwithdraw({
                        mobile: this.form.mobile,
                        password: this.form.password,
                        code: this.form.code,
                    })
                    uni.hideLoading();
                    uni.showToast({
                        icon: 'none',
                        title: this.$t('tips.success'),
                        position: 'center',
                        duration: 2000
                    })
                    this.show = false;
                } catch (error) {
                    uni.hideLoading();
                    // uni.showToast({
					// 	icon: 'none',
					// 	title: error.msg
					// })
                }
                
			},
            async register() {
                uni.showLoading({
                });
                try {
                    let result = await Register({
                        mobile: this.form.mobile,
                        password: this.form.password,
                        re_password: this.form.re_password,
                        code: this.form.code,
                        invite_code: this.form.invite_code,
                        agent: this.form.agent
                    })
                    uni.hideLoading();
                    // #ifdef APP-PLUS
                    appsFlyer.logEvent(
                        {
                            eventName: "af_complete_registration", // 事件名
                            eventValues: {}, // 事件数据
                        },
                        (e) => {
                            console.log(e);
                        }
                    );
					// #endif
                    uni.showToast({
                        icon: 'none',
                        title: this.$t('tips.success'),
                        position: 'center',
                        duration: 2000
                    })
                    this.currentIndex = 'login'
                    this.show = false;
                } catch (error) {
                    uni.hideLoading();
                }
                
			},
            getCode(val) {
				if (this.showNext) {
					return
				}
                let api;
                if (val == 'reset') {
                    if (this.type == '2') {
                        api = resetwithdrawcode
                    } else {
                        api = sendreset
                    }
                }
                if (val == 'register') {
                    api = sendsms
                }
                if (val == 'login') {
                    api = authentication
                }
				if(!this.phoneReg) {
					uni.showToast({
						icon: 'none',
						title: this.$t('login.lengthtip'),
                        position: 'center',
					})
					return
				}
				if (this.$refs.uCode.canGetCode) {
					uni.showLoading()
					api({
						mobile: this.form.mobile,
					}).then(() => {
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						uni.showToast({
							icon: 'none',
							title: this.$t('tips.success'),
                            position: 'center',
	                        duration: 2000,
						})
						// this.showCodeTip = true
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					}).catch((error) => {
                        uni.hideLoading();
                    })
					setTimeout(() => {
			
					}, 2000);

				} else {
					uni.showToast({
						icon: 'none',
						title: this.$t('login.send_error'),
                        position: 'center',
	                    duration: 2000,
						mask: true,
					})
				}
			},
            codeChange(text) {
				this.tips = text;
			},
            end() {
                this.showNext = false;
				// this.$u.toast('倒计时结束');
			},
			start() {
                this.showNext = true;
				// this.$u.toast('倒计时开始');
			},
            backToHome () {
                let pages = getCurrentPages()
				// console.log(pages, pages.length);
				let prePage = pages[pages.length - 2];
                if (!prePage) {
                    uni.reLaunch({
                        url: '/pages/home/home'
                    });
                }
                uni.navigateBack({
                });
			},
            back() {
				let pages = getCurrentPages()
				// console.log(pages, pages.length);
				let prePage = pages[pages.length - 2];
				uni.reLaunch({
                     url: '/pages/home/home'
                });
			},
		},
	}
</script>

<style lang="scss" scoped>
    .main {
        overflow: hidden;
    }
    .tab-box {
        display: flex;
        justify-content: center;
        font-size: 36rpx;
        font-weight: 400;
        padding-bottom: 19rpx;
        .tab {
            font-size: 36rpx;
            font-weight: 400;
            padding-bottom: 19rpx;
            margin: 0 84rpx;
            color:#AAAAAA;
            &-active {
                color:#0F0F0E;
                border-bottom: 5rpx solid #0F0F0E;
            }
        }
        
    }
    .input-box {
        background: #ECECEC;
        padding : 0 30rpx;
        width: 100%;
        border-radius: 10rpx;
        display: flex;
        align-items: center;
        flex: 1;
        image {
            margin-left: 30rpx;
        }
    }
    .backicon {
        position:fixed;
        top:106rpx;
        left:40rpx;
    }
	.withdraw-box{
        margin: auto;
        margin-top: 230rpx;
        padding: 30rpx 0;
		width: 660rpx;
		border-radius: 20rpx;
		overflow: hidden;
		text-align: center;
        
		.withdraw-tittle{
			font-size: 36rpx;
			font-family: Rubik;
			font-weight: 400;
			color: #0F0F0E;
			margin: 42rpx  0rpx ;
			line-height: 36rpx;
			text-align: center;
		}
		.send{
			font-size: 26rpx;
			font-family: Rubik;
			font-weight: 300;
			color: #FC3E32;
			margin: 30rpx 30rpx 30rpx;
			text-align: left;
		}
        .code{
            margin: 30rpx 30rpx 0;
            display: flex;
            align-items: center;
        }
        .otp{
            width: 120rpx;
            height: 90rpx;
            
            border-radius: 10rpx;
            text-align: center;
            margin-left: 20rpx;
            line-height: 90rpx;
            font-size: 32rpx;
            font-family: Rubik;
            font-weight: 400;
            color: #FFFFFF;
            /deep/ .send_code {
                width: 100%;
			}
            
        }
        .link {
            text-decoration: underline;
            color: #E6201C;
            text-align: end;
        }
        .bottom-box {
            justify-content: end;
            display: flex;
            font-size: 30rpx;
            padding:0 30rpx 20rpx;
            margin-top: 50rpx;
        }
	}
    .confirm{
        width: 660rpx;
        height: 90rpx;
        background: $u-type-primary;
        border-radius: 10rpx;
        margin: 60rpx auto;
        font-size: 30rpx;
        font-weight: 400;
        color: #fff;
        text-align: center;
        line-height: 90rpx;
    }
    /deep/.u-mode-center-box{
		background-color: rgba(0,0,0,0);
	}
    .codegray {
		background: rgb(219, 219, 219) !important;
		color: #aaa !important;
	}
	.codeactive {
        background: $zy-color-main!important;
		color: #fff !important;
	}
</style>
